package Client端;

import javax.swing.*;
import java.util.Date;

public class messageThread extends Thread {
    private String receiver;
    private String sender;
    private JTextArea area;
    private Date preTime = new Date(0);
    private boolean isRenew = true;

    public messageThread(String sender, String receiver, JTextArea area) {
        this.sender = sender;
        this.receiver = receiver;
        this.area = area;
        area.setText("");
    }

    public static int getStringLengthRegex(String s) {
        s = s.replaceAll("[^\\x00-\\xff]", "**");
        int length = s.length();
        return length;
    }

    public void endThread() {
        isRenew = false;
    }

    private void renewMessage(Date time1, Date time2) {
        String[][] info;
        if (receiver.length() == 8) info = ClientDeal.get(sender, receiver, time1, time2);
        else info = ClientDeal.getGroupInfo(receiver, time1, time2);
        StringBuilder text = new StringBuilder(100);
        int len;
        for (int i = 0; i < info.length; i++) {
            len = (10 - getStringLengthRegex(info[i][0])) * 2;
            System.out.println(len);
            System.out.println(info[i][0].getBytes().length + " |" + info[i][0] + "|");
            text.append(info[i][0]).append(String.format("%" + len + "s", "")).append("：").append(info[i][2]).append("\n");
        }
        area.append(text.toString());
    }

    public void renewMessage() {
        Date t = new Date();
        renewMessage(preTime, t);
        preTime = t;
    }

    @Override
    public void run() {
        super.run();
        while (isRenew) {
            renewMessage();
            try {
                sleep(5000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
